package de.openlaboratory.xmleditor.xml;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import de.openlaboratory.util.XmlFileUtilities;

public class EntityConstructor
{
	public static void getNode(String xmlFile, String name, String value)
			throws TransformerException, ParserConfigurationException, SAXException, IOException
	{
		Document doc = XmlFileUtilities.getDocument(xmlFile);

		NodeList nodes = doc.getElementsByTagName("jobs");

		Text nam = doc.createTextNode(name);
		Element nameNode = doc.createElement("name");
		nameNode.appendChild(nam);

		Text val = doc.createTextNode(value);
		Element valueNode = doc.createElement("value");
		valueNode.appendChild(val);

		Element adNode = doc.createElement("advertisement");
		adNode.appendChild(nameNode);
		adNode.appendChild(valueNode);

		nodes.item(0).appendChild(adNode);

		// nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));

		DOMSource source = new DOMSource(doc);

		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

		StreamResult result = new StreamResult(xmlFile);

		transformer.transform(source, result);
	}
}
